import { reqregister } from "../../http/api";
import { Toast } from "antd-mobile";

const initState = {
  user: {
    phone: "",
    nickname: "",
    password: "",
  },
};

const TYPES = {
  REGISTER_CHANGE_USER: "REGISTER_CHANGE_USER",
};

const reducer = (state = initState, action) => {
  switch (action.type) {
    case TYPES.REGISTER_CHANGE_USER:
      return {
        ...state,
        user: {
          ...state.user,
          [action.key]: action.value,
        },
      };
    default:
      return state;
  }
};

export const actions = {
  changeUser: (key, value) => ({
    type: TYPES.REGISTER_CHANGE_USER,
    key,
    value,
  }),
  doRegister: (push) => {
    return (dispatch,getState) => {
      let user = getUser(getState());
      reqregister(user).then((res) => {
        if (res.data.code === 200) {
          Toast.show({
            content: res.data.msg,
          });
          push("/login");
        }
      });
    };
  },
};

export const getUser = state => state.register.user;
export default reducer;
